package nasif.cn.imagewikis.image;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ListenerChain {
	final Lock lock = new ReentrantLock();
	List<Listener> chain = new ArrayList<Listener>();

	public boolean execute() {
		boolean flag = false;
		try {
			flag = lock.tryLock(30, TimeUnit.SECONDS);
		} catch (InterruptedException e) {
			Logger logger = LoggerFactory.getLogger(this.getClass());
			logger.error(e.getMessage());
		}
		if (flag) {
			for (Listener listener : chain) {
				listener.handle();
			}
		}
		return flag;
	}

	public boolean add(Listener add) {
		boolean flag = false;
		flag = lock.tryLock();
		if (flag) {
			chain.add(add);
			lock.unlock();
		}
		return flag;
	}

	public boolean remove(Listener remove) {
		boolean flag = false;
		flag = lock.tryLock();
		if (flag) {
			Iterator<Listener> iter = chain.iterator();
			while (iter.hasNext()) {
				Listener listener = iter.next();
				if (remove == listener) {
					chain.remove(remove);
				}
			}
		}
		return flag;
	}
}
